import storage from 'store'
import { login, loginCode } from '@/api/login'
import { queryRoleUser , queryRoleResource , queryUserAllResource } from '@/api/power';
import { queryMember } from '@/api/member';
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    roleUrls: [],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_ROLE_URL: (state, roleUrls) => {
      state.roleUrls = roleUrls
    }
  },

  actions: {
    // 账号密码登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          if(response.success){
            console.log(response,'response')
            // storage.set(ACCESS_TOKEN, response[ACCESS_TOKEN], response.expires_in)
            sessionStorage.setItem(ACCESS_TOKEN,response[ACCESS_TOKEN])
            commit('SET_TOKEN', response[ACCESS_TOKEN])
            resolve()
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 验证码登录、注册
    LoginCode({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginCode(userInfo).then(response => {
          if(response.success){
            console.log(response,'response')
            // storage.set(ACCESS_TOKEN, response[ACCESS_TOKEN], response.expires_in)
            sessionStorage.setItem(ACCESS_TOKEN,response[ACCESS_TOKEN])
            commit('SET_TOKEN', response[ACCESS_TOKEN])
            resolve()
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户权限信息
    GetInfo ({ commit }){
      return new Promise((resolve,reject) => {
        let page = 0
        let roleList = []
        const phone = sessionStorage.getItem('loginPhone')
        const fn = () => {
          queryMember({'brandId':global.brandId,phone:phone})
          .then(response => {
            if(response.success){
              if(response.data.content.length == 0){
                reject('暂未获取到用户信息')
              }
              const userId = response.data.content[0].userId
              sessionStorage.setItem('userId',userId);
              queryUserAllResource()
              .then(res=>{
                if(res.success){
                  roleList = res.data.map(item=>{
                    return item.resourceTag
                  })
                  if(roleList.length == 0){
                    reject('当前用户暂无登录权限！')
                  }else{
                    commit('SET_ROLES', roleList)
                    resolve(roleList)
                  }
                }else{
                  reject('暂未获取到可访问的资源信息！')
                }
              })
            }
          })
        }
        fn()
      })
    },

    // 获取用户信息
    GetInfo1 ({ commit }) {
      return new Promise((resolve, reject) => {
        const phone = sessionStorage.getItem('loginPhone')
        if(!phone){
          reject('暂未获取到用户信息')
        }
        // 根绝手机号获取用户的userId
        queryMember({'brandId':global.brandId,phone:phone}).then(response => {
          if(response.success){
            if(response.data.content.length == 0){
              reject('暂未获取到用户信息')
            }
            const userId = response.data.content[0].userId
            sessionStorage.setItem('userId',userId);
            根据userId获取用户的角色信息
            queryRoleUser({'userId':userId})
            .then(roleConfig=>{
              if(roleConfig.success){
                if(roleConfig.data.content.length > 0){
                  const roleId = roleConfig.data.content[0].roleId
                  // 根绝角色ID获取该角色可以访问的资源信息
                  let page = 0
                  let roleList = []
                  let roleUrlList = []
                  const fn = () => {
                    queryRoleResource({'roleId':roleId,'size':99,'page':page})
                    .then(res=>{
                      if(res.success){
                        if(page == 0){
                          roleList = res.data.content.map(item=>{
                            return item.resourceTag
                          })
                          // roleUrlList = res.data.content.map(item=>{
                          //   return item.url
                          // })
                        }else{
                          const data = res.data.content.map(item=>{
                            return item.resourceTag
                          })
                          // const urlList = res.data.content.map(item=>{
                          //   return item.url
                          // })
                          roleList = [...roleList,...data]
                          // roleUrlList = [...roleUrlList,...urlList]
                        }
                        if((page + 1) * 99 >= res.data.totalElements){
                          commit('SET_ROLES', roleList)
                          // commit('SET_ROLE_URL',roleUrlList)
                          resolve(roleList)
                        }else{
                          page++
                          fn()
                        }
                      }else{
                        reject('暂未获取到可访问的资源信息！')
                      }
                    })
                  }
                  fn()
                }else{
                  reject('暂未获取用户的权限信息！')
                }
                
              }else{
                reject(roleConfig.errMessage)
              }
            })
          }else{
            reject(response.errMessage)
          }
          
          // 根据角色获取该角色的资源信息

          // if (result.role && result.role.permissions.length > 0) {
          //   const role = result.role
          //   role.permissions = result.role.permissions
          //   role.permissions.map(per => {
          //     if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
          //       const action = per.actionEntitySet.map(action => { return action.action })
          //       per.actionList = action
          //     }
          //   })
          //   role.permissionList = role.permissions.map(permission => { return permission.permissionId })
          //   commit('SET_ROLES', result.role)
          //   commit('SET_INFO', result)
          // } else {
          //   reject(new Error('getInfo: roles must be a non-null array !'))
          // }

          // commit('SET_NAME', { name: result.name, welcome: welcome() })
          // commit('SET_AVATAR', result.avatar)

          // resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        // logout(state.token).then(() => {
        //   commit('SET_TOKEN', '')
        //   commit('SET_ROLES', [])
        //   storage.remove(ACCESS_TOKEN)
        //   resolve()
        // }).catch(() => {
        //   resolve()
        // }).finally(() => {
        // })
        commit('SET_TOKEN', '')
        commit('SET_ROUTERS', [])
        commit('SET_ROLES', [])
        commit('SET_ROLE_URL', [])
        // storage.clearAll()
        resolve()
      })
    }

  }
}

export default user
